TOOLCHAIN_DIR_EXT = ${mode}/${toolchain}
SOURCES_CPP_NO_DIR = $(notdir $(SOURCES_CPP))
OBJECTOUTPUTDIR = $(abspath ${builddir}/$(subst ${rootdir},,${CURDIR})/${TOOLCHAIN_DIR_EXT}/obj)
TARGETDIR = $(dir ${OBJECTOUTPUTDIR})
OBJECTS = $(SOURCES_CPP_NO_DIR:%.cpp=$(OBJECTOUTPUTDIR)/%.o)

DEPLIBS = $(foreach dep,${DEPS},$(addprefix ${builddir}/, $(addsuffix .a, $(addsuffix /$(addprefix ${TOOLCHAIN_DIR_EXT}/libcrocodylus_,$(notdir ${dep})), ${dep}))))

LIBDIR = ${builddir}/$(subst ${rootdir}/,,$(CURDIR))
LIBNAME = ${LIBDIR}/${TOOLCHAIN_DIR_EXT}/libcrocodylus_$(notdir ${LIBDIR}).a

.PHONY: ${DEPS} clean_deps clean_obj clean

$(OBJECTOUTPUTDIR)/%.d: %.cpp
	@set -e; rm -f $@; \
	echo Dep $(@F); \
	test -d $(OBJECTOUTPUTDIR) || mkdir -p $(OBJECTOUTPUTDIR); \
	$(CC) $(DEPENDSWITCHES) $(CPP_FLAGS) $< > $@.$$$$; \
	sed 's,\(.*\)\.o[ :]*,$(OBJECTOUTPUTDIR)/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$

ifneq ($(MAKECMDGOALS),clean)
-include $(SOURCES_CPP_NO_DIR:%.cpp=$(OBJECTOUTPUTDIR)/%.d)
endif

${DEPS}:
	@echo Component $(addprefix ${rootdir}/,$@)
	${MAKE} -C $(addprefix ${rootdir}/,$@) || exit 1;

${OBJECTOUTPUTDIR}/%.o: %.cpp
	@echo C++ "("${CC}")" $(@F)
	test -d ${OBJECTOUTPUTDIR} || mkdir -p ${OBJECTOUTPUTDIR}
	${CC} ${CPP_FLAGS} $< -o $@

${LIBNAME}: ${OBJECTS}
	@echo lib "("${AR}") -> " $(@D)"/"$(@F)
	test -d $(@D) || mkdir -p $(@D)
	${AR} ${LIBNAME} ${OBJECTS}

${TARGETDIR}/${TARGET}: ${OBJECTS} ${DEPS}
	@echo Linking $(@F) "-> " ${TARGETDIR}/${TARGET}
	${LD} ${OBJECTS} ${LD_FLAGS} ${DEPLIBS} -o ${TARGETDIR}/${TARGET}
	-$(call STRIP,${TARGETDIR}/${TARGET})
ifneq ($(strip ${CONFIG}),)
	-cp -u -L -R -f ${CONFIG} ${TARGETDIR}
endif

all: ${TARGETDIR}/${TARGET}

lib: ${LIBNAME}

clean_deps:
	@for dep in ${DEPS}; \
        do \
            echo Cleaning Component $$dep; \
            ( ${MAKE} -C ${rootdir}/$$dep clean_obj ) || exit 1; \
	done ;

clean_obj:
	rm -f ${OBJECTS}

clean: clean_deps
	rm -f ${OBJECTS}
	rm -f ${TARGETDIR}/${TARGET}
